package com.xumingxun.aibox.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xumingxun.aibox.context.Context;
import com.xumingxun.aibox.dao.ApplicationRepository;
import com.xumingxun.aibox.domain.dto.Result;
import com.xumingxun.aibox.domain.entity.Application;
import com.xumingxun.aibox.domain.node.StartNode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ApplicationController {

    @Resource
    ApplicationRepository applicationRepository;

    @PostMapping("/application/chat_workflow/open")
    public Object chatWorkflowOpen(@RequestBody JSONObject body){
        JSONArray edges = body.getJSONArray("edges");

        Map<String,String> edgeMapper=new HashMap<>();
        for(int i=0;i<edges.size();i++){
            JSONObject item=edges.getJSONObject(i);
            String sourceAnchorId= StrUtil.strip(item.getString("sourceAnchorId"),"_right");
            String targetAnchorId=StrUtil.strip(item.getString("targetAnchorId"),"_left");
            edgeMapper.put(sourceAnchorId,targetAnchorId);
        }

        JSONArray nodes = body.getJSONArray("nodes");

        Context context=new Context();
        for(int i=1;i<nodes.size();i++){
            JSONObject item= nodes.getJSONObject(i);
            String type=item.getString("type");
            String id=item.getString("id");
            JSONObject propertiesObj= item.getJSONObject("properties");

            if(item.equals("start-node")){
                StartNode startNode=new StartNode(context);
                JSONObject config = propertiesObj.getJSONObject("config");

            }
        }


        return Result.success();
    }

    @DeleteMapping("/application/{applicationId}")
    public Object delete(@PathVariable("applicationId")String applicationId){
        applicationRepository.deleteById(applicationId);
        return Result.success(true);
    }

    @PostMapping("/application")
    public Object post(@RequestBody JSONObject body){
        body.put("clean_time",180);
        body.put("create_time",new Date().toString());
        body.put("file_upload_enable",false);
        body.put("file_upload_setting",new HashMap<>());
        body.put("icon","/ui/favicon.ico");
        body.put("model",null);
        String applicaitonId= UUID.randomUUID().toString();
        body.put("id",applicaitonId);

        applicationRepository.save(new Application().setId(applicaitonId).setJson(body.toJSONString()));
        return Result.success(body);
    }

    @PutMapping("/application/{applicationId}")
    public Object put(@PathVariable("applicationId") String applicaitonId,@RequestBody JSONObject body){

        Application app= applicationRepository.findById(applicaitonId).get();
        JSONObject jsonObject= JSONObject.parseObject(app.getJson());
        jsonObject.put("work_flow",body.getJSONObject("work_flow"));

        applicationRepository.save(new Application().setId(applicaitonId).setJson(jsonObject.toJSONString()));
        return Result.success();
    }

    @GetMapping("/application/{current}/{size}")
    public Result page(@PathVariable("current")Integer current,@PathVariable("size")Integer size) {
        PageRequest pageRequest = PageRequest.of(current-1, size);
        Page<Application> applications = applicationRepository.findAll(pageRequest);

        List<JSONObject> records= applications.get().map(item->JSONObject.parseObject(item.getJson())).collect(Collectors.toList());

        Map<String,Object> data=new HashMap<>();
        data.put("current",current);
        data.put("size",size);
        data.put("total",applications.getTotalElements());
        data.put("records",records);

        return Result.success(data);
    }

    @GetMapping("/application/{applicationId}")
    public Result applicationId(@PathVariable(value = "applicationId")String applicationId){
        Application app= applicationRepository.findById(applicationId).get();
        return Result.success(JSONObject.parseObject(app.getJson()));
    }

    @GetMapping("/application/{applicationId}/access_token")
    public Object applicationToken(@PathVariable("applicationId")String applicationId){
        return JSONObject.parseObject("{\n" +
                "    \"code\": 200,\n" +
                "    \"message\": \"\\u6210\\u529f\",\n" +
                "    \"data\": {\n" +
                "        \"application_id\": \""+applicationId+"\",\n" +
                "        \"access_token\": \"25f377df91ffb8e5\",\n" +
                "        \"is_active\": true,\n" +
                "        \"access_num\": 100,\n" +
                "        \"white_active\": false,\n" +
                "        \"white_list\": [],\n" +
                "        \"show_source\": false,\n" +
                "        \"language\": null\n" +
                "    }\n" +
                "}");
    }
    @GetMapping("/application/{applicationId}/statistics/chat_record_aggregate_trend")
    public Object applicationTrend(@PathVariable("applicationId")String applicationId){
        return JSONObject.parseObject("{\n" +
                "    \"code\": 200,\n" +
                "    \"message\": \"\\u6210\\u529f\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-21\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-22\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-23\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-24\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-25\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-26\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-27\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        },\n" +
                "        {\n" +
                "            \"star_num\": 0,\n" +
                "            \"trample_num\": 0,\n" +
                "            \"tokens_num\": 0,\n" +
                "            \"chat_record_count\": 0,\n" +
                "            \"customer_num\": 0,\n" +
                "            \"day\": \"2025-04-28\",\n" +
                "            \"customer_added_count\": 0\n" +
                "        }\n" +
                "    ]\n" +
                "}");
    }
    @GetMapping("/application/{applicationId}/function_lib")
    public Object functionLib(@PathVariable("applicationId")String applicationId) throws IOException {
        return JSONObject.parseObject("{\n" +
                "    \"code\": 200,\n" +
                "    \"message\": \"\\u6210\\u529f\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "            \"id\": \"73d26178-14f2-11f0-bfe6-0242ac110003\",\n" +
                "            \"name\": \"sql\\u67e5\\u8be2\\u5668\",\n" +
                "            \"desc\": \"\",\n" +
                "            \"code\": \"import re\\nimport requests\\n\\ndef cc(json_str):\\n    pattern = re.compile(r'```sql(.*?)```', re.DOTALL)\\n    match = pattern.search(json_str)\\n    if match:\\n        sql = match.group(1)\\n        json_obj = {}\\n        json_obj['sql']=sql.replace('\\\\n',' ')\\n        resp = requests.post('https://xumingxun.com/sql.php',json=json_obj)\\n        if resp.status_code ==  200:\\n            return resp.text\\n    return False\\n\\n# str=\\\"\\u8981\\u67e5\\u8be2\\u516c\\u53f8\\u5458\\u5de5\\u4eba\\u6570\\uff0c\\u6211\\u9700\\u8981\\u7edf\\u8ba1 `t_staff` \\u8868\\u4e2d\\u6240\\u6709\\u6709\\u6548\\uff08\\u672a\\u903b\\u8f91\\u5220\\u9664\\uff09\\u7684\\u5458\\u5de5\\u8bb0\\u5f55\\u6570\\u91cf\\u3002\\u4ee5\\u4e0b\\u662f\\u76f8\\u5e94\\u7684SQL\\u67e5\\u8be2\\uff1a\\\\n\\\\n```sql\\\\nSELECT COUNT(*) AS total_employees\\\\nFROM t_staff\\\\nWHERE data_status = 1;\\\\n```\\\\n\\\\n\\u8fd9\\u4e2aSQL\\u67e5\\u8be2\\u4f1a\\uff1a\\\\n1. \\u4ece\\u5458\\u5de5\\u8868 `t_staff` \\u4e2d\\u7edf\\u8ba1\\u8bb0\\u5f55\\u6570\\u91cf\\\\n2. \\u53ea\\u8ba1\\u7b97 `data_status = 1`\\uff08\\u6709\\u6548\\uff09\\u7684\\u5458\\u5de5\\\\n3. \\u8fd4\\u56de\\u603b\\u5458\\u5de5\\u6570\\u4f5c\\u4e3a `total_employees`\\\"\\n\\n# cc(str)\",\n" +
                "            \"input_field_list\": [\n" +
                "                {\n" +
                "                    \"name\": \"json_str\",\n" +
                "                    \"type\": \"string\",\n" +
                "                    \"source\": \"reference\",\n" +
                "                    \"is_required\": true\n" +
                "                }\n" +
                "            ],\n" +
                "            \"permission_type\": \"PRIVATE\",\n" +
                "            \"is_active\": true,\n" +
                "            \"user_id\": \"f0dd8f71-e4ee-11ee-8c84-a8a1595801ab\",\n" +
                "            \"create_time\": \"2025-04-09T11:26:40.630274+08:00\",\n" +
                "            \"update_time\": \"2025-04-09T11:26:40.630326+08:00\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"id\": \"b2805214-0c5e-11f0-a556-0242ac11000e\",\n" +
                "            \"name\": \"\\u6839\\u636e\\u57ce\\u5e02\\u67e5\\u8be2\\u5929\\u6c14\",\n" +
                "            \"desc\": \"\",\n" +
                "            \"code\": \"import requests\\nimport json\\n\\ndef call(json_str):\\n    obj=json.loads(json_str)\\n    resp = requests.get(\\\"https://xumingxun.com/weather.php?city=\\\"+str(obj['city']))\\n    return resp.text\",\n" +
                "            \"input_field_list\": [\n" +
                "                {\n" +
                "                    \"name\": \"json_str\",\n" +
                "                    \"type\": \"string\",\n" +
                "                    \"source\": \"reference\",\n" +
                "                    \"is_required\": true\n" +
                "                }\n" +
                "            ],\n" +
                "            \"permission_type\": \"PRIVATE\",\n" +
                "            \"is_active\": true,\n" +
                "            \"user_id\": \"f0dd8f71-e4ee-11ee-8c84-a8a1595801ab\",\n" +
                "            \"create_time\": \"2025-03-29T13:28:50.970601+08:00\",\n" +
                "            \"update_time\": \"2025-03-29T13:28:50.970652+08:00\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"id\": \"8c60a1a2-0c5d-11f0-b817-0242ac11000e\",\n" +
                "            \"name\": \"\\u6839\\u636e\\u673a\\u6784id\\u67e5\\u8be2\\u673a\\u6784\\u4fe1\\u606f\",\n" +
                "            \"desc\": \"\",\n" +
                "            \"code\": \"import requests\\nimport json\\n\\ndef call(json_str):\\n    obj=json.loads(json_str)\\n    resp = requests.get(\\\"https://xumingxun.com/api.php?orgId=\\\"+str(obj['orgId']))\\n    return resp.text\",\n" +
                "            \"input_field_list\": [\n" +
                "                {\n" +
                "                    \"name\": \"json_str\",\n" +
                "                    \"type\": \"string\",\n" +
                "                    \"source\": \"reference\",\n" +
                "                    \"is_required\": true\n" +
                "                }\n" +
                "            ],\n" +
                "            \"permission_type\": \"PRIVATE\",\n" +
                "            \"is_active\": true,\n" +
                "            \"user_id\": \"f0dd8f71-e4ee-11ee-8c84-a8a1595801ab\",\n" +
                "            \"create_time\": \"2025-03-29T13:20:37.512965+08:00\",\n" +
                "            \"update_time\": \"2025-03-29T13:20:37.513017+08:00\"\n" +
                "        }\n" +
                "    ]\n" +
                "}");
    }
    @GetMapping("/application/{applicationId}/application")
    public Object applicationApplication(@PathVariable("applicationId")String applicationId) throws IOException {
        return JSONObject.parseObject(FileUtil.readString(ResourceUtils.getFile("classpath:application4.json"), "utf-8"));
    }
    @GetMapping("/application/{applicationId}/model")
    public Object applicationModel(@PathVariable("applicationId")String applicationId){
        return JSONObject.parseObject("{\"code\": 200, \"message\": \"\\u6210\\u529f\", \"data\": []}");
    }
}
